<!-- ObjectSelect.vue -->
<template>
    <select
      v-model="selectedValue"
      @change="handleChange"
    >
      <option
        v-for="option in options"
        :key="option[selectConfig.id]"
        :value="stringifyValue(option)"
      >

      <slot name="option" :option="option">
        {{ option[selectConfig.label] }}
      </slot>
      </option>
    </select>
 

  </template>
  
  <script setup>

import { computed } from 'vue'
  
  const props = defineProps({
    modelValue: {
      type: Object,
      default: () => ({})
    },
    options: {
      type: Array,
      required: true
    },
    selectConfig:{
      type:Object,
      default:{
        label:"label",
        id:"id"
      }
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'change'])

  // 将对象转换为 JSON 字符串用于 option value
  const stringifyValue = (option) => {
    return JSON.stringify(option)
  }
  
  // 计算属性处理双向绑定
  const selectedValue = computed({
    get() {
      return JSON.stringify(props.modelValue)
    },
    set(newValue) {
      try {
        const parsedValue = JSON.parse(newValue)
        let keyValue = parsedValue[props.selectConfig.id]
        console.log('props.selectConfig.id', props.selectConfig.id)
    
        emit('update:modelValue', keyValue)
      } catch (e) {
        console.error('JSON parse error:', e)
      }
    }
  })
  
  // 处理 change 事件
  const handleChange = (event) => {
    try {
      const selectedObject = JSON.parse(event.target.value)
      emit('change', selectedObject)
    } catch (e) {
      console.error('JSON parse error:', e)
    }
  }
  </script>